<template>
  <div class="expansion-panel">
    <div class="panel-header">
      <h3 class="panel-title">
        <el-icon><CopyDocument /></el-icon>
        AI图片扩展
      </h3>
      <div class="panel-actions">
        <el-button 
          type="primary" 
          :icon="MagicStick"
          :loading="generating"
          @click="handleGenerate"
          :disabled="!selectedImage"
        >
          {{ generating ? '生成中...' : '开始扩展' }}
        </el-button>
        <el-button 
          :icon="RefreshRight"
          @click="handleRegenerate"
          :disabled="!hasGeneratedImages || generating"
        >
          重新生成
        </el-button>
      </div>
    </div>
    
    <!-- 扩展配置 -->
    <div class="expansion-config">
      <div class="config-section">
        <div class="config-title">
          <el-icon><Setting /></el-icon>
          扩展配置
        </div>
        
        <div class="config-content">
          <!-- 生成数量 -->
          <div class="config-group">
            <label class="config-label">生成数量:</label>
            <el-slider
              v-model="expansionConfig.count"
              :min="1"
              :max="10"
              :step="1"
              show-stops
              show-input
              @change="handleConfigChange"
            />
            <div class="config-hint">
              建议生成1-4张图片，数量越多耗时越长
            </div>
          </div>
          
          <!-- 扩展风格 -->
          <div class="config-group">
            <label class="config-label">扩展风格:</label>
            <el-radio-group v-model="expansionConfig.style" @change="handleConfigChange">
              <div class="style-options">
                <el-radio-button label="similar">相似风格</el-radio-button>
                <el-radio-button label="artistic">艺术风格</el-radio-button>
                <el-radio-button label="realistic">写实风格</el-radio-button>
                <el-radio-button label="cartoon">卡通风格</el-radio-button>
                <el-radio-button label="vintage">复古风格</el-radio-button>
                <el-radio-button label="modern">现代风格</el-radio-button>
              </div>
            </el-radio-group>
          </div>
          
          <!-- 自定义提示词 -->
          <div class="config-group">
            <label class="config-label">自定义提示词:</label>
            <el-input
              v-model="expansionConfig.customPrompt"
              type="textarea"
              :rows="4"
              placeholder="可选：输入自定义提示词来指导AI生成特定风格的图片，例如：'增加更多色彩'、'改变背景为自然风景'等..."
              @input="handleConfigChange"
            />
          </div>
          
          <!-- 高级选项 -->
          <div class="config-group">
            <el-collapse>
              <el-collapse-item title="高级选项" name="advanced">
                <div class="advanced-options">
                  <div class="option-row">
                    <label>创意程度:</label>
                    <el-slider
                      v-model="expansionConfig.creativity"
                      :min="0"
                      :max="100"
                      :step="10"
                      show-input
                      @change="handleConfigChange"
                    />
                    <span class="option-hint">数值越高，生成的图片越有创意</span>
                  </div>
                  
                  <div class="option-row">
                    <label>保真度:</label>
                    <el-slider
                      v-model="expansionConfig.fidelity"
                      :min="0"
                      :max="100"
                      :step="10"
                      show-input
                      @change="handleConfigChange"
                    />
                    <span class="option-hint">数值越高，生成的图片越接近原图</span>
                  </div>
                  
                  <div class="option-row">
                    <el-checkbox 
                      v-model="expansionConfig.preserveColors"
                      @change="handleConfigChange"
                    >
                      保持原图色调
                    </el-checkbox>
                  </div>
                  
                  <div class="option-row">
                    <el-checkbox 
                      v-model="expansionConfig.enhanceQuality"
                      @change="handleConfigChange"
                    >
                      增强图片质量
                    </el-checkbox>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 生成进度 -->
    <div class="generation-progress" v-if="generating || generationProgress.show">
      <div class="progress-header">
        <div class="progress-title">
          <el-icon><Loading /></el-icon>
          生成进度
        </div>
        <div class="progress-info">
          {{ generationProgress.current }}/{{ generationProgress.total }}
        </div>
      </div>
      
      <el-progress 
        :percentage="progressPercentage" 
        :status="generationProgress.status"
        :stroke-width="8"
      />
      
      <div class="progress-details">
        <div class="progress-text">{{ generationProgress.message }}</div>
        <div class="progress-time" v-if="generationProgress.estimatedTime">
          预计剩余时间: {{ generationProgress.estimatedTime }}
        </div>
      </div>
    </div>
    
    <!-- 生成历史 -->
    <div class="generation-history" v-if="historyImages.length > 0">
      <div class="history-header">
        <div class="history-title">
          <el-icon><Clock /></el-icon>
          历史记录 ({{ historyImages.length }})
        </div>
        <el-button 
          text 
          size="small"
          @click="loadMoreHistory"
          v-if="hasMoreHistory"
        >
          加载更多
        </el-button>
      </div>
      
      <div class="history-grid">
        <div
          v-for="image in historyImages"
          :key="image.id"
          class="history-item"
          @click="useHistoryImage(image)"
        >
          <div class="history-image">
            <img :src="image.generatedImageUrl" :alt="`生成图片 ${image.id}`" />
            <div class="history-overlay">
              <el-button type="primary" :icon="Plus" size="small">
                使用此图
              </el-button>
            </div>
          </div>
          <div class="history-info">
            <div class="history-meta">
              <el-tag size="small">{{ getStyleText(image.generationParams) }}</el-tag>
              <span class="history-time">{{ formatTime(image.createdAt) }}</span>
            </div>
            <div class="similarity-score" v-if="image.similarityScore">
              相似度: {{ Math.round(image.similarityScore * 100) }}%
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="!generating && !hasGeneratedImages && historyImages.length === 0" class="empty-state">
      <el-icon size="48" color="rgba(255,255,255,0.5)"><Picture /></el-icon>
      <h3>开始图片扩展</h3>
      <p>选择图片并点击"开始扩展"来生成相似图片</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  CopyDocument, MagicStick, RefreshRight, Setting, Loading, Clock,
  Plus, Picture
} from '@element-plus/icons-vue'
import type { 
  ImageModel, 
  GeneratedImageModel, 
  ImageGenerationRequest 
} from '@/types'
import { formatTime } from '@/utils'

interface Props {
  selectedImage?: ImageModel
  loading?: boolean
}

interface Emits {
  (e: 'generate', config: ImageGenerationRequest): void
  (e: 'regenerate', config: ImageGenerationRequest): void
  (e: 'use-history', image: GeneratedImageModel): void
  (e: 'load-history', imageId: number): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const generating = ref(false)
const hasGeneratedImages = ref(false)
const historyImages = ref<GeneratedImageModel[]>([])
const hasMoreHistory = ref(false)

const expansionConfig = ref<ImageGenerationRequest>({
  originalImageId: 0,
  count: 2,
  style: 'similar',
  customPrompt: '',
  creativity: 50,
  fidelity: 70,
  preserveColors: true,
  enhanceQuality: true
} as any)

const generationProgress = reactive({
  show: false,
  current: 0,
  total: 0,
  status: 'active' as 'active' | 'success' | 'exception',
  message: '正在生成图片...',
  estimatedTime: ''
})

// 计算属性
const progressPercentage = computed(() => {
  if (generationProgress.total === 0) return 0
  return Math.round((generationProgress.current / generationProgress.total) * 100)
})

// 监听选中图片变化
watch(() => props.selectedImage, (newImage) => {
  if (newImage) {
    expansionConfig.value.originalImageId = newImage.id
    loadHistory()
  }
}, { immediate: true })

// 方法
const handleGenerate = () => {
  if (!props.selectedImage) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  generating.value = true
  generationProgress.show = true
  generationProgress.current = 0
  generationProgress.total = expansionConfig.value.count
  generationProgress.status = 'active'
  generationProgress.message = '正在生成图片...'
  
  // 估算时间
  const estimatedSeconds = expansionConfig.value.count * 30 // 每张图片约30秒
  generationProgress.estimatedTime = `${Math.ceil(estimatedSeconds / 60)}分钟`
  
  emit('generate', { ...expansionConfig.value })
}

const handleRegenerate = () => {
  if (!props.selectedImage) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  generating.value = true
  generationProgress.show = true
  generationProgress.current = 0
  generationProgress.total = expansionConfig.value.count
  generationProgress.status = 'active'
  
  emit('regenerate', { ...expansionConfig.value })
}

const handleConfigChange = () => {
  // 配置变化时的处理
}

const loadHistory = () => {
  if (props.selectedImage) {
    emit('load-history', props.selectedImage.id)
  }
}

const loadMoreHistory = () => {
  // 加载更多历史记录
}

const useHistoryImage = (image: GeneratedImageModel) => {
  emit('use-history', image)
  ElMessage.success('已添加历史图片到当前结果')
}

const getStyleText = (params: string) => {
  try {
    const config = JSON.parse(params || '{}')
    switch (config.style) {
      case 'similar': return '相似风格'
      case 'artistic': return '艺术风格'
      case 'realistic': return '写实风格'
      case 'cartoon': return '卡通风格'
      case 'vintage': return '复古风格'
      case 'modern': return '现代风格'
      default: return '未知风格'
    }
  } catch {
    return '未知风格'
  }
}

// 暴露方法给父组件
defineExpose({
  updateProgress: (current: number, message?: string) => {
    generationProgress.current = current
    if (message) {
      generationProgress.message = message
    }
    
    if (current >= generationProgress.total) {
      generationProgress.status = 'success'
      generationProgress.message = '生成完成'
      generating.value = false
      hasGeneratedImages.value = true
      
      setTimeout(() => {
        generationProgress.show = false
      }, 2000)
    }
  },
  setError: (message: string) => {
    generationProgress.status = 'exception'
    generationProgress.message = message
    generating.value = false
    
    setTimeout(() => {
      generationProgress.show = false
    }, 3000)
  },
  setHistoryImages: (images: GeneratedImageModel[]) => {
    historyImages.value = images
  },
  setGenerating: (status: boolean) => {
    generating.value = status
  }
})
</script>

<style scoped>
.expansion-panel {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.panel-actions {
  display: flex;
  gap: 10px;
}

/* 扩展配置样式 */
.expansion-config {
  margin-bottom: 30px;
}

.config-section {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
}

.config-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  color: rgba(255, 255, 255, 0.9);
}

.config-content {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.config-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.config-label {
  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
}

.config-hint {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-top: -8px;
}

.style-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.advanced-options {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-top: 15px;
}

.option-row {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-row label {
  font-size: 13px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
}

.option-hint {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
}

/* 生成进度样式 */
.generation-progress {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 30px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.progress-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.progress-info {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.progress-details {
  margin-top: 15px;
  text-align: center;
}

.progress-text {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 5px;
}

.progress-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

/* 历史记录样式 */
.generation-history {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 20px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.history-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.history-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.history-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.history-image {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}

.history-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.history-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.history-item:hover .history-overlay {
  opacity: 1;
}

.history-info {
  padding: 10px;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.history-time {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.6);
}

.similarity-score {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.7);
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.7);
}

.empty-state h3 {
  margin: 20px 0 10px 0;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .expansion-panel {
    padding: 15px;
  }
  
  .panel-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .panel-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .style-options {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .history-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
  }
}
</style>